package se.hrbustrc.hlgshopping.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import se.hrbustrc.hlgshopping.entity.Address;
import se.hrbustrc.hlgshopping.service.AddressService;
import se.hrbustrc.hlgshopping.utils.Result;
import se.hrbustrc.hlgshopping.utils.UserContext;

import java.util.List;

@RestController
@Tag(name = "地址管理", description = "送货地址管理")
@RequestMapping("/address")
public class AddressController315 {
    
    @Autowired
    private AddressService addressService;
    
    /**
     * 添加送货地址
     * @param address 送货地址信息
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public Result addAddress(@RequestBody Address address) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 设置地址关联的用户ID
            address.setUserid(userId);
            
            boolean success = addressService.save(address);
            if (success) {
                return new Result().ok("地址添加成功");
            } else {
                return new Result().error("地址添加失败");
            }
        } catch (Exception e) {
            return new Result().error("地址添加异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID删除送货地址
     * @param aid 地址ID
     * @return 是否删除成功
     */
    @DeleteMapping("/delete/{aid}")
    public Result deleteAddress(@PathVariable("aid") Long aid) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 确保用户只能删除自己的地址
            Address address = addressService.getById(aid);
            if (address == null) {
                return new Result().error("地址不存在");
            }
            
            if (!address.getUserid().equals(userId)) {
                return new Result().error("无权限删除该地址");
            }
            
            boolean success = addressService.removeById(aid);
            if (success) {
                return new Result().ok("地址删除成功");
            } else {
                return new Result().error("地址删除失败");
            }
        } catch (Exception e) {
            return new Result().error("地址删除异常: " + e.getMessage());
        }
    }
    
    /**
     * 更新送货地址信息
     * @param address 更新的地址信息
     * @return 是否更新成功
     */
    @PutMapping("/update")
    public Result updateAddress(@RequestBody Address address) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 确保用户只能更新自己的地址
            Address existingAddress = addressService.getById(address.getAid());
            if (existingAddress == null) {
                return new Result().error("地址不存在");
            }
            
            if (!existingAddress.getUserid().equals(userId)) {
                return new Result().error("无权限更新该地址");
            }
            
            // 设置地址关联的用户ID
            address.setUserid(userId);
            
            boolean success = addressService.updateById(address);
            if (success) {
                return new Result().ok("地址更新成功");
            } else {
                return new Result().error("地址更新失败");
            }
        } catch (Exception e) {
            return new Result().error("地址更新异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询送货地址
     * @param aid 地址ID
     * @return 地址信息
     */
    @GetMapping("/get/{aid}")
    public Result getAddressById(@PathVariable("aid") Long aid) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 获取地址信息
            Address address = addressService.getById(aid);
            if (address == null) {
                return new Result().error("地址不存在");
            }
            
            // 确保用户只能查看自己的地址
            if (!address.getUserid().equals(userId)) {
                return new Result().error("无权限查看该地址");
            }
            
            return new Result().ok(address);
        } catch (Exception e) {
            return new Result().error("查询地址异常: " + e.getMessage());
        }
    }
    
    /**
     * 查询当前用户的所有送货地址
     * @return 地址列表
     */
    @GetMapping("/list")
    public Result getAllAddresses() {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 查询当前用户的所有地址
            List<Address> addresses = addressService.lambdaQuery()
                    .eq(Address::getUserid, userId)
                    .list();
            return new Result().ok(addresses);
        } catch (Exception e) {
            return new Result().error("查询地址列表异常: " + e.getMessage());
        }
    }
}
